<?php
/*
	Aurus CMS - free OOP CMS
	Copyright (C) 2010  Nestor Yanchuk

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('ROOT')) die();

class Upload {
	public static $maxSizeMB = 4;
	public static $allowedExt = array('zip','rar','exe','doc','pdf');
	public static $allowedImgExt = array('png','jpg','gif','bmp');
	
	/**
	 * Upload file on server
	 *
	 * @param string $index - index of current file in $_FILES array
	 * @param string $module - module which uploads the file
	 * @param string $module_material_id - id of post
	 * @param int $user - uploaded user id (don't change)
	 * @return mixed - ID of file or false
	 */
	public static function uploadFile($index,$module,$module_material_id = 0,int $user = null){
		if (!isset($_FILES[$index])){
			return false;
		}
		
		$ext = strtolower(getExtention($_FILES[$index]['name']));
		$servName = au_date('d_m_Y',TIME).'_'.$module.'_'.uniqid().$ext;

		if (!$user) {
			$user = Users::getInstance()->getLoggedUsersData('uid');
		}
		
		if (self::is_image($_FILES[$index]['type'])) {
			
			if (move_uploaded_file($_FILES[$index]['tmp_name'],ROOT.'/uploads/images/'.$servName)){
				Mysql::getInstance()->insert('uploads',array(
				'module' => $module,
				'mod_material_id' => $module_material_id,
				'time' => TIME,
				'name' => Mysql::getInstance()->escape($_FILES[$index]['name']),
				'path' => '/uploads/images/'.$servName,
				'user' => $user,
				'downloads' => '0',
				'mime' => $_FILES[$index]['type'],
				));
			}
		} else {
			if (move_uploaded_file($_FILES[$index]['tmp_name'],ROOT.'/uploads/files/'.$servName)){
				Mysql::getInstance()->insert('uploads',array(
				'module' => $module,
				'mod_material_id' => $module_material_id,
				'time' => TIME,
				'name' => Mysql::getInstance()->escape($_FILES[$index]['name']),
				'path' => '/uploads/files/'.$servName,
				'user' => $user,
				'downloads' => '0',
				'mime' => $_FILES[$index]['type']
				));
			}
		}
	}
	
	public static function approve_upload_file($fid,$module_material_id){
		Mysql::getInstance()->update('uploads', array('mod_material_id' => $module_material_id), 'f_id='.$fid);
	}
	
	/**
	 * 
	 * @return void
	 */
	public static function clean_trash(){
		
	}
	/**
	 * check if is image
	 *
	 * @param string $mimetype
	 * @return bool - TRUE if is image
	 */
	private static function is_image($mimetype){
		return substr($mimetype,0,5) == 'image';
	}
	
	public static function getUploadFiles($module,$module_material_id = 0,$user = null){
		if (!$user) {
			$user = Users::getInstance()->getLoggedUsersData('uid');
		}

		$data = Mysql::getInstance()->select('uploads','*','module=\''.$module.'\' AND mod_material_id=\''.$module_material_id.'\' AND user='.$user);
		return $data;
	}
	
	
	/**
	 * Завантаження картинки на сервер.
	 *
	 * @param string $gName - індекс картинки в масиві $_FILES
	 * @param string $destDir - тека призначення
	 * @param int $w - максимальна ширина картинки
	 * @param int $h - максимальна висота картинки
	 * @param string $prefix - префікс який буде додано до імені картинки
	 * @param string $newName - нова назва картинки, якщо не передано , згенерується автоматично
	 * @return mixed:
	 * int -1 - нема відправки картинки
	 * int -2 - надісланий файл не є картинкою
	 * int -3 - висота або ширина картинки завеликі
	 * int -4 - невідомий тип картинки
	 * int -5 - невідома помилка
	 * string - шлях до картинки, все пройшло добре
	 */
	public static function uploadImage($gName,$destDir,$w,$h,$prefix = '',$newName = ''){
		if (!isset($_FILES[$gName])) {
			return -1;
		}
		if (substr($_FILES[$gName]['type'],0,5) !== 'image') {
			return -2;
		}
		$im = getimagesize($_FILES[$gName]['tmp_name']);

		if ($im[0] > $w or $im[1] > $h) {
			return -3;
		}

		$ext = '.'.getExtention($_FILES[$gName]['name']);
		if (!$ext) {
			switch ($_FILES[$gName]['type']){
				case "image/gif": $ext = '.gif';
				case "image/png": $ext = '.png';
				case "image/jpeg": $ext = '.jpg';
				default: return -4;
			}
		}

		if (!$newName) {
			$newName = time();
		}

		if (move_uploaded_file($_FILES[$gName]['tmp_name'],$destDir.$prefix.$newName.$ext)) {
			return $prefix.$newName.$ext;
		}
		return -5;
	}
}